/**
 * @Creator: eyes
 * @Date: 2019/12/23
 * 「核心页面概览」整个模块的状态管理
 */

import {useState, useEffect} from 'react';
import {TIME_DURATION, CORE_PAGES_CONFIG, PERFORMANCE_TARGET_TYPE} from '~/utils/const';
import {getCorePagesPerformance} from '~/service/performance';
import {generateLatestWeek, calcDateRangeStr, dateFormat} from '../utils';

export default () => {
    // 初始化时, dateRange默认为过去七天, 查看未读则默认为按天查看
    const [dateRange, setDateRange] = useState(generateLatestWeek());
    const [duration, setDuration] = useState(TIME_DURATION.ONE_DAY);

    // 性能数据
    const [performances, setPerformances] = useState(null);

    const [loading, setLoading] = useState(true);

    const updateTimeInfo = ({dateRange, duration}) => {
        if (dateRange) {
            setDateRange(dateRange);
        }
        if (duration) {
            setDuration(duration);
        }
    };

    // 获取和管理性能数据
    useEffect(() => {
        (async () => {
            setLoading(true);

            const [startTime, endTime] = calcDateRangeStr(dateRange);

            // 对于CORE_PAGES_CONFIG中的每一个Page, 调用API获取其性能数据
            const performances = await Promise.all(
                CORE_PAGES_CONFIG.map(({bizTypeName, bizName, path}) =>
                    getCorePagesPerformance({
                        targetType: PERFORMANCE_TARGET_TYPE.TTFP,
                        bizTypeName,
                        bizName,
                        path,
                        startTime,
                        endTime,
                        timeType: duration,
                    })),
            );
            // 将获取的性能数据, 填充到CORE_PAGES_CONFIG中, 以data字段表示.
            setPerformances(CORE_PAGES_CONFIG.map(
                (page, index) => ({
                    ...page,
                    path: page.bizName + page.path,
                    data: performances[index].data
                        && performances[index]
                            .data
                            .performanceMeasures
                            .map(_ => ({
                                ..._,
                                datetime: dateFormat(_.datetime, duration),
                            }))
                        || [],
                }),
            ));

            setLoading(false);
        })();
    }, [dateRange, duration]);

    return [
        {
            dateRange,
            duration,
            loading,
            performances,
        },
        updateTimeInfo,
    ];
};
